package com.example.androidmvp;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract;

/**
 * Created by kerray on 2016/9/25.
 */
public class ContactsModelImpl implements ContactsModel
{
    @Override
    public void getContacts(final int num, final onContactsListener listener, final Context context)
    {

        new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                switch (num)
                {
                    case 1:
                        listener.onNotError();
                        break;
                    case 2:
                        listener.onNullError();
                        break;
                    case 3:
                        listener.onSuccess();
                        break;
                    case 4:
                        final List<SortModel> model = getSortModel(context);
                        listener.onGetContactsSuccess(model);
                        break;
                }
            }
        }, 500);
    }

    public static List<SortModel> getSortModel(Context context){
        long currentTimeMillis = System.currentTimeMillis();
        List<SortModel> _contacts = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor query = contentResolver.query(Uri.parse("content://com.android.contacts/raw_contacts"),
          new String[]{ ContactsContract.DeletedContacts.CONTACT_ID}, null, null, null);

        while (query.moveToNext()) {
            String contactId = query.getString(0);
            Cursor query1 = contentResolver.query(Uri.parse("content://com.android.contacts/data"), new String[] {
              ContactsContract.Data.DATA1,
              ContactsContract.Data.MIMETYPE }, "raw_contact_id = ?", new String[] { contactId }, null);

            int _Id = Integer.parseInt(contactId);
            SortModel info = new SortModel();
            while (query1.moveToNext()) {
                info.id = _Id;
                String data1 = query1.getString(0);
                String mimetype = query1.getString(1);
                if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mimetype)) {
                    info.phone = data1;
                } else if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mimetype)) {
                    info.name = data1;
                }
                info.enabled = false;
            }
            _contacts.add(info);
        }
        long l = System.currentTimeMillis() - currentTimeMillis;
        //GLog.i(context, "耗时 = " + (l / 1000) + "s");
        return _contacts;
    }
}
